package org.hmh.base;

import java.util.Arrays;

/**
 * Created this one by HMH on 2018/1/20.
 */
public class MergeSort {

    public static void sort(int[] arr) {
        mergeSort(arr, 0, arr.length - 1);
    }

    public static void mergeSort(int arr[], int left, int right) {
        if (left >= right) {
            return;
        }
        int mid = left + (right - left) / 2;
        mergeSort(arr, left, mid);
        mergeSort(arr, mid + 1, right);
        mergeArr(arr, left, right);
    }

    public static void mergeArr(int arr[], int left, int right) {
        int temp[] = new int[right - left + 1];
        System.arraycopy(arr, left, temp, 0, temp.length);
        int mid = (right - left) / 2;
        int i = 0;
        int j = mid + 1;
        int cur = 0;
        while (i <= mid || j < temp.length) {
            if (i == mid + 1) {
                arr[left + cur++] = temp[j++];
            } else if (j == temp.length) {
                arr[left + cur++] = temp[i++];
            } else if (temp[i] > temp[j]) {
                arr[left + cur++] = temp[j++];
            } else {
                arr[left + cur++] = temp[i++];
            }
        }
    }

    public static void main(String[] args) {
        int arr[] = {15,1, 6, 7, 3, 2, 4, 5, 3, 123, 12, 3, 235, 6, 5};
        sort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
